module AuthlogicMethods
  def current_user_session
    return @current_user_session if defined?(@current_user_session)
    @current_user_session = UserSession.find
  end

  def current_user
    return @current_user if defined?(@current_user)
    @current_user = current_user_session && current_user_session.user
  end

  def require_login
    unless current_user
      store_location
      flash[:notice] = "You must be logged in to access this page"
      redirect_to login_url#new_user_session_url
      return false
    end
  end

  def require_login_with_notice(notice)
    unless current_user
      store_location
      flash[:notice] = notice
      redirect_to new_user_session_url
      return false
    end
  end

  def store_location
    session[:return_to] = request.request_uri
  end

  def redirect_back_or_default(default)
    redirect_to(session[:return_to] || default)
    session[:return_to] = nil
  end

  def require_no_user
    if current_user
      store_location
      flash[:notice] = "You must be logged out to access this page"
      redirect_to my_account_url
      return false
    end
  end

  def access_denied
    if current_user
      flash[:notice]='Access denied.'
      redirect_to root_url
    else
      flash[:notice]='Access denied. Try to log in first.'
      redirect_to_login_url
    end
  end
end
